#include "role.h"
#include <gb/gb.h>

uint8_t sprite_size = 8;

void move_character(Role *character, uint8_t x, uint8_t y) {
  if (character->sprite_run_status == 2) {
    character->sprite_run_status = 0;
  } else {
    ++character->sprite_run_status;
  }
  set_sprite_tile(character->sprite_id[0], character->sprite_run[character->sprite_run_status]);
  set_sprite_tile(character->sprite_id[1], character->sprite_run[character->sprite_run_status] + 2);
  if (x < character->x && character->direction == Right) {
    set_sprite_prop(character->sprite_id[0], get_sprite_prop(character->sprite_id[0]) | S_FLIPX);
    set_sprite_prop(character->sprite_id[1], get_sprite_prop(character->sprite_id[1]) | S_FLIPX);
    character->direction = Left;
  }
  if (x > character->x && character->direction == Left) {
    // !(S_FLIPX)
    set_sprite_prop(character->sprite_id[0], get_sprite_prop(character->sprite_id[0]) & 0xdfu);
    set_sprite_prop(character->sprite_id[1], get_sprite_prop(character->sprite_id[1]) & 0xdfu);
    character->direction = Right;
  }

  if (character->x != x || character->y != y) {
    switch (character->direction) {
      case Right:
        move_sprite(character->sprite_id[0], x - 4, y);
        move_sprite(character->sprite_id[1], x + sprite_size - 4, y);
        break;
      case Left:
        move_sprite(character->sprite_id[0], x, y);
        move_sprite(character->sprite_id[1], x - sprite_size, y);
        break;
      default:
        break;
    }
  }
}

void initRole(Role *role, uint8_t x, uint8_t y) {
  role->x = 0;
  role->y = 0;
  role->sprite_run[0] = 8;
  role->sprite_run[1] = 12;
  role->sprite_run[2] = 16;
  role->sprite_run_status = 0;
  set_sprite_tile(0, role->sprite_run[role->sprite_run_status]);
  role->sprite_id[0] = 0;
  set_sprite_prop(0, 0);
  set_sprite_tile(1, role->sprite_run[role->sprite_run_status] + 2);
  role->sprite_id[1] = 1;
  role->direction = Right;
  set_sprite_prop(1, 0);
  move_character(role, x, y);
  role->x = x;
  role->y = y;
}
